package git.bankview.wl.common;

import java.util.*;
import java.text.*;
import java.sql.*;

import laya.semi.process.*;

import git.bankview.sl.db.*;

import org.apache.log4j.Logger;

public class DeleteTableActivity
	implements IGenericClassActivity
{
	private static Logger log = Logger.getLogger(DeleteTableActivity.class);

	public void execute(IProcessContext oCtx)
		throws Exception
	{
		Connection oConn = DBConnectionFactory.getCoreConnection();

		try
		{
			String[] vParam = oCtx.getActivityParameter().split(":");
			String oTableName = vParam[0];
			String[] vConditionField = vParam[1].split(",");
			String oResultField = (2 < vParam.length ? vParam[2] : null);
			
			StringBuffer oSql = new StringBuffer("DELETE FROM ").append(oTableName);
			StringBuffer oSqlW = new StringBuffer();

			for (int i = 0; i < vConditionField.length; ++i)
			{
				String oCondi = vConditionField[i];
				if (0 < oCondi.trim().length())
				{
					Object oCondVal = oCtx.getField(oCondi);
					if (null != oCondVal)
					{
						Object[] vField = null;
						if (oCondVal.getClass().isArray())
						{
							vField = (Object[])oCondVal;
						}
						else
						{
							vField = new Object[] {oCondVal};
						}
						
						if (0 < vField.length)
						{
							if (0 < oSqlW.length())
								oSqlW.append(" AND ");
								
							oSqlW.append(oCondi).append(" IN (");
							
							for (int j = 0; j < vField.length; ++j)
							{
								if (0 == j)
									oSqlW.append("?");
								else
									oSqlW.append(", ?");
							}
							
							oSqlW.append(")");
						}
					}
				}
			}
			
			if (0 < oSqlW.length())
			{
				oSql.append(" WHERE ").append(oSqlW);
			}
			
			log.debug(oSql);
			oSqlW = new StringBuffer(); // for log
			PreparedStatement ps = oConn.prepareStatement(oSql.toString());
			int nParamIdx = 0;
			for (int i = 0; i < vConditionField.length; ++i)
			{
				String oCondi = vConditionField[i];
				if (0 < oCondi.trim().length())
				{
					Object oCondVal = oCtx.getField(oCondi);
					if (null != oCondVal)
					{
						Object[] vField = null;
						if (oCondVal.getClass().isArray())
						{
							vField = (Object[])oCondVal;
						}
						else
						{
							vField = new Object[] {oCondVal};
						}
						
						if (0 < vField.length)
						{
							for (int j = 0; j < vField.length; ++j)
							{
								ps.setObject(++nParamIdx, vField[j]);
								oSqlW.append("{").append(vField[j]).append("}");
							}
						}
					}
				}
			}
			log.debug(oSqlW);
			int nEffectRowCount = ps.executeUpdate();
			if (null != oResultField)
			{
				oCtx.setField(oResultField, new Integer(nEffectRowCount));
			}
		}
		finally
		{
			oConn.close();
		}
	}
}
